package com.summerbird.mallchat.common.common.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.summerbird.mallchat.common.common.exception.HttpErrorEnum;
import com.summerbird.mallchat.common.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    public static final String HEADER_AUTHORIZATION = "Authorization";
    public static final String AUTHORIZATION_SCHEMA = "Bearer ";
    public static final String ATTRIBUTE_UID = "uid";

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        Long uid = loginService.getValidUid(token);
        // 用户是登录态
        if(Objects.nonNull(uid)){
            // 获取uid 和 ip
            request.setAttribute(ATTRIBUTE_UID, uid);
        }else{ // 未登录
            // 检查是否是公开路径
            boolean isPublicURI = isPublicURI(request);
            if(!isPublicURI){//又没有登录态，又不是公开路径，直接401
                HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是否是公共方法
     * @param request
     * @return
     */
    private boolean isPublicURI(HttpServletRequest request) {
        String uri = request.getRequestURI();
        String[] split = uri.split("/");
        return split.length > 3 && "public".equals(split[3]);
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HEADER_AUTHORIZATION);
        return Optional.ofNullable(token)
                .filter(h -> h.startsWith(AUTHORIZATION_SCHEMA))
                .map(h -> h.replaceFirst(AUTHORIZATION_SCHEMA, ""))
                .orElse(null);
    }
}
